
//
//  MyAddressListViewController.m
//  LuxuryGoods
//
//  Created by DCQ on 2018/5/25.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "MyAddressListViewController.h"
#import "MyAddressCell.h"
#import "EditAddressListViewController.h"
#import "AddressListModel.h"
#import "UserInfoModel.h"

NSString * const MyAddressCellIdentifier = @"MyAddressCellIdentifier";
@interface MyAddressListViewController ()
@property(nonatomic, copy)AddressListModel * listModel;
@property(nonatomic, assign) AddressListVCStyle  style;
@end

@implementation MyAddressListViewController
- (instancetype)initWithStyle:(AddressListVCStyle)style{
    self = [super init];
    if (self) {
        self.style =  style;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setNavigationItemTitle:@"收货地址"];
    [self setupRightItem];
    [self requestAddressList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(requestAddressList) name:@"UPDATE_ADDRESS_NOTIFICATION" object:nil];
}
- (void)requestAddressList{
    
    WEAKSELF
    [[MainApi sharedInstance] postPath:@"User/getAddressList" params:@{@"token":UserInfo.userToken} resultBlock:^(NSDictionary *responseObject, NSError *error) {
        STRONGSELF
        NSLog(@"%@===",responseObject);
        if (responseObject) {
          
            strongSelf.listModel = [[AddressListModel alloc]initWithDictionary:responseObject error:nil];
            
        }
        [strongSelf.tableView reloadData];
    }];
}
- (void)setupRightItem{
    UIBarButtonItem * barItem = [[UIBarButtonItem alloc]initWithTitle:@"添加新地址" style:UIBarButtonItemStylePlain target:self action:@selector(gotoNewAddressVC)];
    barItem.tintColor = UIColorFromRGB(0x666666);
    [barItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil] forState:UIControlStateNormal];
    [barItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil] forState:UIControlStateSelected];
    self.navigationItem.rightBarButtonItem = barItem;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)registerCell{
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MyAddressCell class]) bundle:nil] forCellReuseIdentifier:MyAddressCellIdentifier];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSInteger sections =   self.listModel.data.count;
 
    return sections;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger rows = 1;
    
    return rows;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = nil;
    MyAddressCell * tempCell  = [tableView dequeueReusableCellWithIdentifier:MyAddressCellIdentifier];
    tempCell.indexPath = indexPath;
    tempCell.btnBlock = ^(MyAddressButtonType type, NSIndexPath *indexPath) {
        if (type == MyAddressButtonType_edit) {
            [self gotoEditAddressVC:indexPath];
        }else if (type == MyAddressButtonType_delete){
            [self deleteAddress:indexPath];
        }else if (type == MyAddressButtonType_changeDefault){
            
            [self changeDefaultAddress:indexPath];
        }
    };
    [tempCell setupAddress:self.listModel.data[indexPath.section]];
    cell = tempCell;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.style == AddressListVCStyle_changeOrderAddress) {
        AddressModel * model = self.listModel.data[indexPath.section];
        NSDictionary * addressDic =  @{@"address_id":model.address_id,@"consignee":model.consignee,@"phone":model.phone,@"location":model.location,@"detail_address":model.detail_address};
        if (self.selectedBlock) {
          self.selectedBlock(addressDic);
        }
        [self backViewController];
    }
    
}

- (void)gotoEditAddressVC:(NSIndexPath *)indexPath{
    AddressModel * model = self.listModel.data[indexPath.section];
    EditAddressListViewController * tempVC = [[EditAddressListViewController alloc]initWithData:model WithStyle:AddressListStyle_edit];
    [self pushViewController:tempVC];
}
- (void)gotoNewAddressVC{
    EditAddressListViewController * tempVC = [[EditAddressListViewController alloc]initWithData:nil WithStyle:AddressListStyle_new];
    [self pushViewController:tempVC];
}

- (void)deleteAddress:(NSIndexPath *)indexPath{
    
    AddressModel * model = self.listModel.data[indexPath.section];
 
    [[MainApi sharedInstance] postPath:@"User/delAddress" params:@{@"token":UserInfo.userToken,@"address_id":model.address_id} resultBlock:^(NSDictionary *responseObject, NSError *error) {
        
        NSLog(@"%@===",responseObject);
        [self requestAddressList];
    }];
}

- (void)changeDefaultAddress:(NSIndexPath *)indexPath{
    AddressModel * model = self.listModel.data[indexPath.section];
    
    if ([model.is_default isEqualToString:@"1"]) {
        
        return ;
    }
    NSDictionary * params = @{@"token":UserInfo.userToken,
                              @"address_id":model.address_id,
                              @"consignee":model.consignee,
                              @"phone":model.phone,
                              @"location":model.location,
                              @"detail_address":model.detail_address,
                              @"is_default":@"1"
                              };
    
    [[MainApi sharedInstance] postPath:@"User/addOrEditAddress" params:params resultBlock:^(NSDictionary *responseObject, NSError *error) {
        
        NSLog(@"%@===",responseObject);
        [self requestAddressList];
    }];
    
}
- (NSString *)getDescriptionText{
    return @"请添加新地址";
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
